import datetime

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect
from django.conf import settings
from web import models


# 将我们自己放到request的属性进行封装
class Saas(object):
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None

class AuthMiddleWare(MiddlewareMixin):

    def process_request(self, request):

        request.saas = Saas()

        user_id = request.session.get('user_id', 0)  # 如果获取不到就是0
        user = models.UserInfo.objects.filter(id=user_id).first()
        request.saas.user = user

        # 获取当前用户访问的url，检查url是否在白名单中
        # print(request.path_info)
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return

        # 如果用户没有登录，则返回登录页面
        if not request.saas.user:
            return redirect('login')

        '''
            # 登录成功后获取当前用户拥有的额度
            _object = models.Transaction.objects.filter(user=user, status=2).order_by('-id').first()
            # 判断是否过期
            current_datetime = datetime.datetime.now()
            if _object.end_datetime and _object.end_datetime < current_datetime:
                # 过期
                _object = models.Transaction.objects.filter(user=user, status=2, price_policy__category=1).first()

            # request.transaction = _object
            request.saas.price_policy = _object.price_policy
        '''

        # 获取当前用户ID值最大（最近交易记录）
        _object = models.Transaction.objects.filter(user=user, status=2).order_by('-id').first()

        if not _object:
            # 没有购买
            request.saas.price_policy = models.PricePolicy.objects.filter(category=1, title="个人免费版").first()
        else:
            # 付费版
            current_datetime = datetime.datetime.now()
            if _object.end_datetime and _object.end_datetime < current_datetime:
                request.saas.price_policy = models.PricePolicy.objects.filter(category=1, title="个人免费版").first()
            else:
                request.saas.price_policy = _object.price_policy

    def process_view(self, request, view, args, kwargs):
        # 判断url是否以manage开头
        if not request.path_info.startswith("/web/manage/"):
            return

        # 判断项目id是否是我创建的或者是我参与的
        project_id = kwargs.get('project_id')
        project_object = models.Project.objects.filter(creator=request.saas.user, id=project_id).first()

        if project_object:
            request.saas.project = project_object
            return

        project_user_object = models.ProjectUser.objects.filter(user=request.saas.user, project_id=project_id).first()

        if project_user_object:
            request.saas.project = project_user_object
            return

        # 禁止访问
        return redirect('project_list')
